﻿using GFluentCode.Tools;
using GFluentCode.Tools.FluentObject;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace GFluentCode.Demo
{
    public partial class FrmSocket : Form
    {
        FluentSocketServer _server;
        string _curId;
        public FrmSocket()
        {
            InitializeComponent();

            _server = new FluentSocketServer(10);
            _server.ReceivedData += _server_ReceivedData;
            _server.AcceptSocket += _server_AcceptSocket;

            //LblMsg.DataBindings.Add("Text",_server,"Msg");
        }

        private void _server_AcceptSocket(FluentSocket socket)
        {
            Invoke(new Action(()=> {
                LbConnector.Items.Insert(0, socket.ID);
            }));
        }

        private void _server_ReceivedData(FluentSocket socket, byte[] data)
        {            
            Invoke(new Action(() =>
            {
                LbInfo.Items.Insert(0, $"{socket.SocketObj.RemoteEndPoint.ToString()}接收：{Encoding.UTF8.GetString(data)}");
            }));
        }

        private void BtnConnect_Click(object sender, EventArgs e)
        {
            if (TxtIP.Text.GIsEmpty(true))
                _server.Start(int.Parse(txtPort.Text));
            else
                _server.Start(TxtIP.Text,int.Parse(txtPort.Text));
        }

        private void BtnSend_Click(object sender, EventArgs e)
        {
            if (_curId.GIsEmpty(true)) return;
            _server.Send(_curId, Encoding.UTF8.GetBytes("1231231231adf"));
        }

        private void LbConnector_Click(object sender, EventArgs e)
        {
            if (LbConnector.SelectedItem == null)
            {
                _curId = string.Empty; 
                return;
            }
            _curId = LbConnector.SelectedItem.ToString();
        }
    }
}
